<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      title="文章详情"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 导航栏 -->
    <div class="article-warp">
      <h1 class="title">{{ article.title }}</h1>
      <van-cell center class="user-info">
        <div slot="title" class="name">{{ article.aut_name }}</div>
        <van-image
          slot="icon"
          class="avatar"
          round
          fit="cover"
          :src="article.aut_photo"
        />
        <div slot="label" class="pubdate">
          {{ article.pubdate | relativeTime }}
        </div>
        <van-button
          class="follow-btn"
          :type="article.is_followed ? 'default' : 'info'"
          :icon="article.is_followed ? '' : 'plus'"
          round
          size="samll"
          :loading="isFollowLoading"
          @click="onFollow"
          >{{ article.is_followed ? "已关注" : "关注" }}</van-button
        >
      </van-cell>
      <div
        class="markdown-body"
        v-html="article.content"
        ref="article-content"
      ></div>

      <!-- 文章评论列表 -->
      <comment-list
        :source="articleId"
        :list="commentList"
        @update-total-count="totalCommentCount = $event"
        @reply-click="onReplyClick"
      />
      <!-- 文章评论列表 -->
    </div>

    <!-- 底部区域 -->
    <div class="article-bottom">
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
        @click="isPostShow = true"
        >写评论</van-button
      >
      <van-icon name="comment-o" :info="totalCommentCount" color="#777" />
      <van-icon
        :color="article.is_collected ? 'orange' : '#777'"
        :name="article.is_collected ? 'star' : 'star-o'"
        @click="onCollect"
      />
      <van-icon
        :color="article.attitude === 1 ? 'hotpink' : '#777'"
        :name="article.attitude === 1 ? 'good-job' : 'good-job-o'"
        @click="onLike"
      />
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- 底部区域 -->

    <!-- 发布评论 -->
    <van-popup v-model="isPostShow" position="bottom">
      <post-comment :target="articleId" @post-success="onPostSuccess" />
    </van-popup>
    <!-- 发布评论 -->

    <!-- 评论回复 -->
    <van-popup v-model="isReplyShow" position="bottom">
      <comment-reply
        v-if="isReplyShow"
        :comment="replyComment"
        :article-id="articleId"
        @close="isReplyShow = false"
      />
    </van-popup>
    <!-- 评论回复 -->
  </div>
</template>


<script>
import "./github-markdown.css";
import {
  getArticleById,
  addCollect,
  deleteCollect,
  addLike,
  deleteLike,
} from "@/api/article";
import { ImagePreview } from "vant";
import { addFollow, deleteFollow } from "@/api/user";
import CommentList from "./component/comment-list.vue";
import PostComment from "./component/post-comment.vue";
import CommentReply from "./component/comment-reply.vue";
// ImagePreview([
//   "https://img01.yzcdn.cn/vant/apple-1.jpg",
//   "https://img01.yzcdn.cn/vant/apple-2.jpg",
// ]);
export default {
  name: "ArticleIndex",
  components: {
    CommentList,
    PostComment,
    CommentReply,
  },
  props: {
    articleId: {
      type: [String, Number, Object],
      required: true,
    },
  },
  data() {
    return {
      article: {}, //文章数据对象
      isFollowLoading: false, //关注用户按钮的loading状态
      isPostShow: false, //控制评论发布显示状态
      commentList: [],
      totalCommentCount: 0,
      isReplyShow: false, //控制回复的显示状态
      replyComment: {}, //当前回复评论对象
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadArticle();
  },
  mounted() {},
  methods: {
    async loadArticle() {
      const { data } = await getArticleById(this.articleId);
      this.article = data.data;

      //获取文章内容DOM容器
      //const articleContent = this.$refs["article-content"];
      //数据改变影响视图更新（DOM数据）不是立即的
      //异步渲染--》$nextTick数据改变后操作DOM

      this.$nextTick(() => {
        //得到所有的img标签
        this.handlePreviewImage();
      });
      // this.handlePreviewImage();

      //循环img ，给img注册点击事件
      //事件处理函数中调用ImagePreview()预览
    },

    handlePreviewImage() {
      const articleContent = this.$refs["article-content"];
      const imgs = articleContent.querySelectorAll("img");
      const imgPaths = [];
      imgs.forEach((img, index) => {
        imgPaths.push(img.src);
        img.onclick = function () {
          ImagePreview({
            images: imgPaths,
            startPosition: index,
          });
        };
      });
    },

    async onFollow() {
      // 开启按钮的 loading 状态
      this.isFollowLoading = true;

      try {
        // 如果已关注，则取消关注
        const authorId = this.article.aut_id;
        if (this.article.is_followed) {
          await deleteFollow(authorId);
        } else {
          // 否则添加关注
          await addFollow(authorId);
        }

        // 更新视图
        this.article.is_followed = !this.article.is_followed;
      } catch (err) {
        console.log(err);
        this.$toast.fail("操作失败");
      }

      // 关闭按钮的 loading 状态
      this.isFollowLoading = false;
    },

    async onCollect() {
      // 这里 loading 不仅仅是为了交互提示，更重要的是请求期间禁用背景点击功能，防止用户不断的操作界面发出请求
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: "操作中...",
        forbidClick: true, // 是否禁止背景点击
      });

      try {
        // 如果已收藏，则取消收藏
        if (this.article.is_collected) {
          await deleteCollect(this.articleId);
          // this.article.is_collected = false
          this.$toast.success("取消收藏");
        } else {
          // 添加收藏
          await addCollect(this.articleId);
          // this.article.is_collected = true
          this.$toast.success("收藏成功");
        }
        this.article.is_collected = !this.article.is_collected;
      } catch (err) {
        console.log(err);
        this.$toast.fail("操作失败");
      }
    },

    async onLike() {
      // 两个作用：1、交互提示 2、防止网络慢用户连续不断的点击按钮请求
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: "操作中...",
        forbidClick: true, // 是否禁止背景点击
      });

      try {
        // 如果已经点赞，则取消点赞
        if (this.article.attitude === 1) {
          await deleteLike(this.articleId);
          this.article.attitude = -1;
          this.$toast.success("取消点赞");
        } else {
          // 否则添加点赞
          await addLike(this.articleId);
          this.article.attitude = 1;
          this.$toast.success("点赞成功");
        }
      } catch (err) {
        console.log(err);
        this.$toast.fail("操作失败");
      }
    },

    onPostSuccess(comment) {
      this.commentList.unshift(comment);

      this.totalCommentCount++;
      this.isPostShow = false;
    },

    onReplyClick(comment) {
      console.log("onReplyClick", comment);
      this.replyComment = comment;
      this.isReplyShow = true;
    },
  },
};
</script>

<style scoped lang="less">
.article-wrap {
  position: fixed;
  left: 0;
  right: 0;
  top: 46px;
  bottom: 44px;
  overflow-y: auto;
}
.article-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  box-sizing: border-box;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 1.17333rem;
  border-top: 0.02667rem solid #d8d8d8;
  background-color: #fff;
}
.comment-btn {
  width: 4.26667rem;
}
.title {
  font-size: 20px;
  color: #3a3a3a;
  padding: 14px;
  background-color: #fff;
  margin: 0;
}
.user-info {
  .avatar {
    width: 35px;
    height: 35px;
    margin-right: 8px;
  }
  .name {
    font-size: 12px;
    color: #333;
  }
  .pubdate {
    font-size: 11px;
    color: #b4b4b4;
  }
  .follow-btn {
    width: 85px;
    height: 29px;
  }
}

.markdown-body {
  padding: 14px;
  background-color: #fff;
}
</style>